package com.itstyle.quartz.job;

import com.itstyle.quartz.entity.QuartzEntityDt;
import com.itstyle.quartz.kettleUtil.DateUtil;
import com.itstyle.quartz.kettleUtil.LogUtil;
import com.itstyle.quartz.kettleUtil.kettleUtil;
import com.itstyle.quartz.service.dao.IJobService;
import org.pentaho.di.core.Result;
import org.quartz.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;

import java.io.Serializable;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.net.UnknownHostException;
import java.util.Date;
import java.util.List;
import java.util.UUID;

/**
 * 实现序列化接口、防止重启应用出现quartz Couldn't retrieve job because a required class was not found 的问题
 * Job 的实例要到该执行它们的时候才会实例化出来。每次 Job 被执行，一个新的 Job 实例会被创建。
 * 其中暗含的意思就是你的 Job 不必担心线程安全性，因为同一时刻仅有一个线程去执行给定 Job 类的实例，甚至是并发执行同一 Job 也是如此。
 * @DisallowConcurrentExecution 保证上一个任务执行完后，再去执行下一个任务，这里的任务是同一个任务
 */
@DisallowConcurrentExecution
public class kettleKtr implements  Job,Serializable  {

    private static final Logger logger = LoggerFactory.getLogger(kettleKtr.class);

    private static final long serialVersionUID = 1L;
    @Autowired
    public IJobService jobService;

    public JobKey jobkey;
    public kettleKtr(){};
    public kettleKtr(JobKey jobkey,IJobService jobService){this.jobkey=jobkey;this.jobService=jobService;};
    @Override
    @Transactional
    public void execute(JobExecutionContext context){
        JobDetail jobDetail = context.getJobDetail();
        JobDataMap dataMap = jobDetail.getJobDataMap();
        JobKey jobkeys = jobDetail.getKey();
        /**
         * 获取任务中保存的方法名字，动态调用方法
         */
        String methodName = dataMap.getString("jobMethodName");
        try {
            kettleKtr job = new kettleKtr(jobkeys,this.jobService);
            Method method = job.getClass().getMethod(methodName);
            method.invoke(job);
        } catch (NoSuchMethodException e) {
            logger.error("KETTLE KTR执行异常，jobkey="+jobkey.toString()+e.getMessage());
        } catch (IllegalAccessException e) {
            logger.error("KETTLE KTR执行异常，jobkey="+jobkey.toString()+e.getMessage());
        } catch (InvocationTargetException e) {
            logger.error("KETTLE KTR执行异常，jobkey="+jobkey.toString()+e.getMessage());
        }
    }

    public Result runKtr(){
        String path=null;
        Result result = null;
        // 不对参数进行处理，约定为ktr不传参数，所有传参数的都为Job任务去执行
        String [] params = null;
        //日志状态信息给定默认值
        String message="任务执行中！";
        //任务状态
        String status="正在执行";
        //使用集群时显示主机IP
        String hostIp = "";
        try {
            hostIp = LogUtil.getLocalhostIp();
        } catch (UnknownHostException e) {
            e.printStackTrace();
        }
       if(this.jobkey != null){
           List<QuartzEntityDt> list = jobService.listJobKettle(this.jobkey);
           String quartzid = UUID.randomUUID().toString().substring(0,10)+DateUtil.getFormatTimeString(new Date(),"yyyyMMddHHmmss");
           if(list != null  && list.size()>0){
               QuartzEntityDt quartz = list.get(0);
                  path = quartz.getKETTLEPATCH();
                  //处理日志信息
                  LogUtil.saveJobKettleLogs(quartz.getKETTLEPATCH(),quartzid,jobkey,jobService,status,null);

                  try {
                      logger.info("KTR任务开始执行：jobkey="+jobkey.toString());
                      result = kettleUtil.runKtr(params,path);
                      logger.info("KTR任务执行结束：jobkey="+jobkey.toString()+"; result"+result.toString());

                      if(result.getResult()){
                          //处理日志信息
                          status="执行成功";
                          message="执行主机IP"+hostIp+"; 任务执行成功!";
                          LogUtil.updateJobKettleLogs(quartzid,jobkey,jobService,status,message);
                      }else {
                          //处理日志信息
                          status="执行失败";
                          message="执行主机IP"+hostIp+"; 执行失败! 请检查执行Ketlle KTR是否有异常。";
                          LogUtil.updateJobKettleLogs(quartzid,jobkey,jobService,status,message);
                      }
                  }catch(Exception e){
                      logger.error("KETTLE KTR执行异常，jobkey="+jobkey.toString()+e.getMessage());
                      //处理日志信息
                      status="执行异常";
                      message="执行主机IP"+hostIp+";"+e.getMessage();
                      LogUtil.updateJobKettleLogs(quartzid,jobkey,jobService,status,message);
                  }

           }

       }
        return result;
    }

    public JobKey getJobkey() {
        return jobkey;
    }

    public void setJobkey(JobKey jobkey) {
        this.jobkey = jobkey;
    }
}